package com.core.cloudbusiness.tool;

import com.core.cloudcommon.context.RequestContext;
import com.core.cloudcommon.security.UserInfo;
import com.core.cloundbusinessapi.system.user.dto.CloudSystemUserDTO;
import org.springframework.stereotype.Component;

/**
 * @author =====Lqj=====
 * @className CommonRequestContext
 * @description
 * @create 2024/12/4 16:19
 **/

@Component
public class CommonRequestContext implements RequestContext {
    private static final ThreadLocal<CloudSystemUserDTO> currentUser = new ThreadLocal<>();

    /**
     * 将当前登陆的用户信息放到线程的上下问中
     *
     * @param user
     */
    public static void setUser(CloudSystemUserDTO user) {
        currentUser.set(user);
    }

    /**
     * 获取当前登陆的用户信息（静态方法）
     *
     * @return
     */
    public static CloudSystemUserDTO getCurrentUser() {
        return currentUser.get();
    }

    /**
     * 清理当前用户信息（静态方法）
     */
    public static void clearUser() {
        currentUser.remove();
    }

    // 实现RequestContext接口
    @Override
    public UserInfo getUser() {
        return currentUser.get();
    }

    @Override
    public void setUser(UserInfo user) {
        if (user instanceof CloudSystemUserDTO) {
            currentUser.set((CloudSystemUserDTO) user);
        }
    }

    @Override
    public void clear() {
        currentUser.remove();
    }
}
